﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TypeRacer.Models;
using WebUtility.Attribute;

namespace TypeRacer.Controllers
{
    public class BookController : BaseController
    {
       
       
        //
        // GET: /Book/

        public ActionResult Index(string sort, string ord)
        {
            var    listBook = Context.Books.ToList();
            ViewData["IsAsc"] = ord != "desc";
            if(!string.IsNullOrEmpty(sort))
            {
                if(typeof(Book).GetProperty(sort) != null)
                {
                    if ((string)TempData["CurrentSortField"] != sort)
                    {
                        listBook = listBook.OrderBy(x => typeof (Book).GetProperty(sort).GetValue(x, null)).ToList();
                        ViewData["IsAsc"] = true;
                    }else
                    {
                        if ((bool)ViewData["IsAsc"])
                        {
                            listBook = listBook.OrderBy(x => typeof(Book).GetProperty(sort).GetValue(x, null)).ToList();
                            ViewData["IsAsc"] = true;
                        }
                        else 
                        {
                            listBook = listBook.OrderByDescending(x => typeof(Book).GetProperty(sort).GetValue(x, null)).ToList();
                            ViewData["IsAsc"] = false;
                        }
                        
                    }
                   
                }

                 ViewData["CurrSortField"] = sort;
                TempData["CurrentSortField"] = sort;

            }
            ViewData["Data"] = listBook;
            return View();
        }

        [AjaxOnly]
        public PartialViewResult Search(string q)
        {
            var searchResult =
                Context.Books.ToList().Where(x => string.IsNullOrEmpty(q) || x.Title.Contains(q) || x.Author.Contains(q));
            return PartialView("_ListOfBook", searchResult);
        }

        public ActionResult AddBook(Book b)
        {

            if(ModelState.IsValid)
            {
                Context.Books.Add(b);
                Context.SaveChanges();
                
            }
            System.Threading.Thread.Sleep(2000);
            return PartialView("_ListOfBook", Context.Books.ToList());
        }

    }
}
